import AntModal from "@/components/pt/dialog/AntModal";
import BizJinjianInfoEditYushenShenheForm from "@/views/biz/jinjianinfo/modules/BizJinjianInfoAddYushenShenqinForm.vue";
import {
  getBizCustomer,
  addBizCustomer,
  updateBizCustomer,
  findMaxSort,
  updateStatus,
  lookPhone,
  lockCustomer,
  playCall,
} from "@/api/biz/bizCustomer";
import {
  addBizCustomerFile,
  listBizCustomerFile,
} from "@/api/biz/bizCustomerFile";
import { listDeptTree } from "@/api/system/dept";
import { listBizCustomerDongtai } from "@/api/biz/bizCustomerDongtai";
import {
  listBizCustomerXiezu,
  addBizCustomerXiezu,
  delBizCustomerXiezu,
} from "@/api/biz/bizCustomerXiezu";
import { listBizXiezu } from "@/api/biz/bizXiezu";
import {
  addBizCustomerShadowInfo,
  listBizCustomerShadowInfo,
} from "@/api/biz/bizCustomerShadowInfo";
import { listBizJinjianInfo } from "@/api/biz/bizJinjianInfo";
import {
  listBizCustomerShadowInfoPinglun,
  addBizCustomerShadowInfoPinglun,
} from "@/api/biz/bizCustomerShadowInfoPinglun";
import { findListByCode } from "@/api/biz/sysArea";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import ChangeUser from "@/views/system/user/modules/ChangeUser";

export default {
  name: "CreateForm",
  props: {
    statusOptions: {
      type: Array,
    },
    typeOptions: {
      type: Array,
    },
    progressOptions: {
      type: Array,
    },
    levelOptions: { type: Array },
    ideasTypeOptions: {
      type: Array,
    },
    zxInfoOptions: {
      type: Array,
    },
    sexOptions: {
      type: Array,
    },
    zhichanInfoOptions: {
      type: Array,
    },
    genjinQuckitInputOptions: {
      type: Array,
    },
    fujianTypeOptions: {
      type: Array,
    },
    isXiezu: {
      type: Boolean,
      default: true,
    },
    companyTypeOptions: {
      type: Array,
    },
    houseTypeOptions: {
      type: Array,
    },
  },
  components: {
    AntModal,
    ChangeUser,
    BizJinjianInfoEditYushenShenheForm,
  },
  data() {
    return {
      showEditModal: false,
      open: false,
      spinning: false,
      ispinglun: false, // 评论是否开启
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      total: 0,
      id: undefined,
      formTitle: "添加客户推送信息",
      // 表单参数
      form: {},
      rules: {
        cusName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "客户电话不能为空", trigger: "blur" },
        ],
        cityName: [
          { required: true, message: "城市区域不能为空", trigger: "blur" },
        ],
        laiyuan: [{ required: true, message: "来源不能为空", trigger: "blur" }],
      },
      customerShadowList: [],
      isinputshow: false,
      infoTabls: "baseinfo",
      isaddimage: false,
      isSms: false,
      edit: false,
      showGenButton: true,
      // 附件列表
      defaultFileList: [],
      // 客户资料的附件列表
      customerFileList: [],
      jinjianTypeOptions: [],
      backTypeOptions: [],
      orgTypeOptions: [],
      carStatusOptions: [],
      sform: {
        level: undefined,
        ideasType: undefined,
        nextTime: undefined,
        mark: undefined,
        takes: undefined,
        progress: undefined,
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        uploadStatus: "",
        fileList: [],
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + storage.get(ACCESS_TOKEN) },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API,
      },
      // 上传附件对话框
      showAddFile: false,
      // 文件上传 内容
      fileform: {
        type: "",
        customerId: "",
        url: "",
      },
      previewImage: "",
      previewVisible: false,
      previewTitle: "",
      xiezuVisible: false, // 协助
      chooseUserVisible: false,
      // 协助客户表单验证
      xiezurules: {
        xiezuUsers: [
          {
            required: true,
            message: "选择协助同事",
            trigger: "change",
          },
        ],
      },
      // xiezuform
      xiezuform: { xiezuUsers: [], remark: "" },
      deptOptions: "",
      xiezuUserList: [],
      xiezuInfoList: [],
      customerInfo: [],
      jinjianInfoList: [],
      customerId: "",
      status: "",
      busTypeOptions: [],
      xiezuList: [],
      // 是否提交按钮
      isShadowSubimt: false,
      // 动态
      customerDongtaiList: [],
      dongtaitotal: 0,
      dongtaiPageNo: 1,
      // 评论
      pinglunList: [],
      isShowPinglun: false,
      // 门店信息
      companyList: [],
      // 区域信息
      cityList: [],
      isLook: false,
    };
  },
  filters: {},
  created() {
    this.getDicts("product_type").then((response) => {
      this.jinjianTypeOptions = response.data;
    });
    this.getDicts("back_type").then((response) => {
      this.backTypeOptions = response.data;
    });
    this.getDicts("org_type_options").then((response) => {
      this.orgTypeOptions = response.data;
    });
    this.getDicts("car_status_options").then((response) => {
      this.carStatusOptions = response.data;
    });
    this.handleGetCompanyList();
    this.handleFindCityList();
  },
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    handleFindCityList() {
      findListByCode().then((res) => {
        this.cityList = res.data;
      });
    },
    handleGetCompanyList() {
      this.getCompanyInfos().then((res) => {
        this.companyList = res.data;
        console.log(res.data);
      });
    },
    handleDongtaiPages(page, pageSize) {
      this.dongtaiPageNo = page;
      listBizCustomerDongtai({
        customerId: this.customerId,
        pageNum: this.dongtaiPageNo,
      }).then((res) => {
        this.customerDongtaiList = res.data.list;
        this.dongtaitotal = res.data.total;
      });
    },
    onClose() {
      this.open = false;
      this.reset();
      this.$emit("close");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("ok");
      this.$emit("close");
    },
    cancelImport() {
      this.$emit("ok");
      this.$emit("close");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        companyId: undefined,

        carModel: undefined,

        cityName: undefined,

        cusName: undefined,

        houseType: undefined,

        phone: undefined,

        price: undefined,

        type: undefined,

        shareDate: undefined,

        accumulation: undefined,

        carStatus: undefined,

        policy: undefined,

        sex: undefined,

        social: undefined,

        dailTime: undefined,

        isDail: undefined,

        clueId: undefined,

        ip: undefined,

        sort: undefined,

        status: undefined,
      };
    },
    // 删除协助人
    handleDeleteCustomerXieZu(id) {
      const that = this;
      this.$confirm({
        title: "确认要执行该操作?",
        onOk: () => {
          delBizCustomerXiezu(id).then((res) => {
            that.$message.success("删除成功");
            that.handleXieZuList(this.customerId);
            that.hanlelistBizCustomerXiezu(this.customerId);
          });
          return new Promise((resolve, reject) => {
            setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
          }).catch(() => console.log("Oops errors!"));
        },
        onCancel() {},
      });
    },
    // 查询协助信息
    handleXieZuList(customerId) {
      listBizXiezu({ customerId: customerId, pageSize: 50 }).then((res) => {
        this.xiezuList = res.data.list;
      });
    },
    // 评论
    handlepinglun(item) {
      const param = { customerId: item.id, content: item.remark };
      addBizCustomerShadowInfoPinglun(param).then((res) => {
        this.$message.success("评论成功");
        this.$emit("ok");
        this.handleGetPingLunList(item, true);
        item.remark = "";
        item.ispinglun = false;
      });
    },
    handcallPhone(item) {
      playCall({ phone: item.phone, id: item.id }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd(status) {
      this.reset();
      this.open = true;
      /** 获取最大编号 */
      findMaxSort().then((response) => {
        this.form.sort = response.data;
      });
      this.form.status = status;
      this.getDicts("laiyuan_self").then((response) => {
        this.busTypeOptions = response.data;
      });
      // this.form.pgPrice = 2;
    },
    // 查看电话
    handleLookPhone(form) {
      lookPhone({ id: form.id }).then((res) => {
        this.isLook = true;
      });
    },
    /**
     * 更新星级
     */
    handlelevelChange(value) {
      this.form.level = value;
      updateBizCustomer(this.form).then((response) => {
        this.$message.success("更新成功", 3);
      });
    },
    /** 新增按钮操作 */
    handleAddImport(status) {
      this.open = true;
      this.status = status;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.spinning = !this.spinning;
      const bizCustomerId = row.id;
      getBizCustomer(bizCustomerId).then((response) => {
        this.form = response.data;
        this.formTitle = "修改客户信息";
        this.spinning = !this.spinning;
      });
    },
    handleShadow(row) {
      this.reset();
      this.open = true;
      this.spinning = !this.spinning;
      const bizCustomerInfoId = row.id;
      this.customerId = row.id;

      // 获取用户信息
      getBizCustomer(bizCustomerInfoId).then((response) => {
        this.form = response.data;
        this.form.isLook = false;
        this.form.otherZc = JSON.parse(this.form.otherZc);
        this.spinning = !this.spinning;
      });
      // 获取跟进信息
      this.getcustomershadow(row.id);

      // 获取文件资料
      this.handlelistBizCustomerFile(row.id);
      // 获取协助信息
      this.hanlelistBizCustomerXiezu(row.id);
      // 查询协助
      this.handleXieZuList(row.id);
    },
    // 获取跟踪信息
    getcustomershadow(customerId) {
      const query = { customerId: customerId, pageSize: 50, pageNo: 1 };
      listBizCustomerShadowInfo(query).then((res) => {
        this.customerShadowList = res.data.list.map((item) => {
          return { ...item, ispinglun: false, isShowPinglun: false };
        });
      });
    },
    // 上传客户附件
    handleChange(info) {
      const status = info.file.status;
      let fileList = [...info.fileList];
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      console.log("file", fileList);
      if (status === "done") {
        this.$message.success(`${info.file.response.msg}`);
        fileList = fileList.slice(-2);
        fileList = fileList.map((file, key) => {
          if (file.response) {
            file.url = file.response.data.url;
            file.thumbUrl = file.response.data.url;
            file.uid = key;
            file.status = "done";
            file.name = file.response.data.fileName;
          }
          return file;
        });
      } else if (status === "error") {
        this.$message.error(`${info.file.name} 文件导入失败！`);
      }
      this.defaultFileList = fileList;
    },
    // 提交跟踪信息
    shadowSubimt() {
      this.isShadowSubimt = true;
      var form = {
        name: this.form.cusName,
        phone: this.form.phone,
        nextTime: this.sform.nextTime,
        // mark: this.sform.mark,
        takes: this.sform.takes,
        customerId: this.form.id,
        progress: this.sform.progress,
        isToHome: this.isaddimage ? 1 : 0,
        isSms: this.isSms ? 1 : 0,
        toHomeTime: this.sform.toHomeTime,
        ideasType: this.sform.ideasType,
        companyNames: JSON.stringify(this.sform.companyNames),
      };

      if (form.isToHome === 1) {
        if (!form.toHomeTime) {
          this.$message.error("请选择上门时间");
          this.isShadowSubimt = false;
          return;
        }
      }
      addBizCustomerShadowInfo(form).then((res) => {
        this.$message.success("添加成功");
        this.$emit("ok");
        this.getcustomershadow(this.form.id);
        this.isinputshow = false;
        this.sform = {
          takes: undefined,
        };
        this.isaddimage = false;
        this.isSms = false;
        this.showGenButton = true;
        this.isShadowSubimt = false;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form));
          if (this.form.id !== undefined) {
            updateBizCustomer(saveForm).then((response) => {
              this.$message.success("修改成功", 3);
              this.open = false;
              this.$emit("ok");
              this.$emit("close");
            });
          } else {
            addBizCustomer(saveForm).then((response) => {
              this.$message.success("新增成功", 3);
              this.open = false;
              this.$emit("ok");
              this.$emit("close");
            });
          }
        } else {
          return false;
        }
      });
    },
    // 转入我的客户
    handleZhuaMyCus(status) {
      var that = this;
      that.ids = this.customerId;
      if (that.ids.length === 0) {
        that.$message.warning("请选择客户", 3);
        return;
      }
      this.$confirm({
        title: "确认要执行该操作?",
        onOk() {
          return updateStatus({ ids: [that.ids], status: status }).then(
            (res) => {
              that.$message.success("操作成功", 3);
              that.$emit("ok");
              that.$emit("close");
            }
          );
        },
        onCancel() {},
      });
    },
    // 申请进件
    handleShowJinjian() {
      if (this.form.yushenStatus === "1") {
        this.$message.warning("已申请预审，请勿重复提交", 3);
        return;
      }
      this.customerInfo = this.form;
      this.showEditModal = true;
      this.$nextTick(() => this.$refs.bizJinjianInfoEditForm.handleAdd());
    },
    // 获取客户文件列表
    handlelistBizCustomerFile(customerId) {
      listBizCustomerFile({ customerId: customerId, pageSize: 50 }).then(
        (res) => {
          if (res.code === 200) this.customerFileList = res.data.list;
        }
      );
    },
    // 计算生日、年龄
    jisuanIdCard(e) {
      console.log(e.target._value);
      const idcard = e.target._value;
      if (idcard.length >= 14) {
        this.form.birthDay =
          idcard.substring(6, 10) +
          "-" +
          idcard.substring(10, 12) +
          "-" +
          idcard.substring(12, 14);
        const nowYear = new Date().getFullYear();
        const chushenYear = idcard.substring(6, 10);
        this.form.age = nowYear - chushenYear;
      }
    },
    // 计算车龄
    onChangeCarAge(date, dateString) {
      const fuckCar = new Date(date).getFullYear();
      const nowCar = new Date().getFullYear();

      if (nowCar - fuckCar > 0) {
        this.form.carAge = nowCar - fuckCar + "年";
      } else {
        if (new Date(date).getMonth() - new Date().getMonth() > 0) {
          this.form.carAge =
            new Date(date).getMonth() - new Date().getMonth() + "月";
        } else {
          this.form.carAge = "当月购买";
        }
      }
    },
    // 文件上传关闭
    handlefileClose() {
      this.showAddFile = false;
    },
    // 点击确定
    handlefileConfirm() {
      this.fileform.customerId = this.form.id;
      if (!this.fileform.type) {
        this.$message.error("请选择文件类型", 3);
        return;
      }
      if (this.defaultFileList.length <= 0) {
        this.$message.error("请上传文件", 3);
        return;
      }
      this.fileform.url = this.defaultFileList[0].url;
      addBizCustomerFile(this.fileform).then((res) => {
        this.$message.success("提交成功", 3);
        this.showAddFile = false;
        this.handlelistBizCustomerFile(this.fileform.customerId);
      });
    },
    // 点击其他的选项卡
    handleGenJincallback(key) {
      console.log(key);
      this.showGenButton = true;
      this.isinputshow = false;

      if (key === "jinjian") {
        listBizJinjianInfo({ customerId: this.customerId }).then((res) => {
          this.jinjianInfoList = res.data.list;
        });
      }
      if (key === "dongtai") {
        listBizCustomerDongtai({
          customerId: this.customerId,
          pageNum: this.dongtaiPageNo,
        }).then((res) => {
          this.customerDongtaiList = res.data.list;
          this.dongtaitotal = res.data.total;
        });
      }
    },
    // 锁定客户
    handleLockCustomer(id, status) {
      var that = this;
      var form = { id: id, isLock: status };
      var message = "";
      if (status === 1) {
        message = "锁定客户";
      }
      if (status === 0) {
        message = "解锁客户";
      }
      this.$confirm({
        title: "确认要" + message + "吗？",
        onOk() {
          return lockCustomer(form).then((res) => {
            that.form.isLock = status;
            that.$message.success(message + "成功", 3);
            // that.$emit("ok");
            // that.$emit("close");
          });
        },
        onCancel() {},
      });
    },
    // 点击跟进按钮
    handleClickGenJin() {
      this.isinputshow = true;
      this.infoTabls = "genjin";
      this.showGenButton = false;
    },
    // 点击编辑
    handleEdit() {
      this.edit = true;
    },
    // 点击取消编辑
    handleCanelEdit() {
      this.edit = false;
    },
    // 点击取消保存
    handleSaveEdit() {
      if (this.form.otherZc) {
        this.form.otherZc = JSON.stringify(this.form.otherZc);
      }
      // const saveForm = JSON.parse(JSON.stringify(this.form));
      if (this.form.id !== undefined) {
        updateBizCustomer(this.form).then((response) => {
          this.$message.success("修改成功", 3);
          this.edit = false;
          this.form.version = this.form.version + 1;
          this.form.otherZc = JSON.parse(this.form.otherZc);
        });
      }
    },
    // 点击跟进快捷输入
    handleGenJinkInput(text) {
      if (this.sform.takes) {
        this.sform.takes = this.sform.takes + " " + text;
      } else {
        this.sform.takes = text;
      }
    },
    // 协助员工
    handleManualShare(user) {
      console.log(user);
      // if (this.xiezuUserList.length > 0) {
      //   for (var i = 0; i < this.xiezuUserList.length; i++) {
      //     for (var j = 0; j < user.length; j++) {
      //       if (this.xiezuUserList[i] === user[j]) {
      //         user.splice(j, 1);
      //       }
      //     }
      //   }
      // }
      // user.map((user) => {
      //   this.xiezuUserList.push(user);
      // });
      this.xiezuUserList = user;
      this.xiezuform.xiezuUsers = this.xiezuUserList.map((item) => {
        return item.id;
      });
      this.xiezuform.xiezuUserNames = this.xiezuUserList.map((item) => {
        return item.name;
      });
    },

    // 获取员工数部门树
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDeptTree("0", 3).then((response) => {
        this.deptOptions = response.data;
        // this.getExpandedKeys(this.deptOptions, 3);
      });
    },
    // 获取用户协助信息
    hanlelistBizCustomerXiezu(id) {
      listBizCustomerXiezu({ customerId: id, pageSize: 500 }).then((res) => {
        this.xiezuInfoList = res.data.list;
      });
    },
    // 添加协助人信息
    handleAddXieZuInfo() {
      this.xiezuform.customerId = this.form.id;
      this.xiezuform.xiezuUserNames = [];
      this.xiezuUserList.map((item) => {
        for (var i = 0; i < this.xiezuform.xiezuUsers.length; i++) {
          if (item.id === this.xiezuform.xiezuUsers[i]) {
            this.xiezuform.xiezuUserNames.push(item.name);
          }
        }
      });
      addBizCustomerXiezu(this.xiezuform).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功", 3);
          this.xiezuVisible = false;
          this.hanlelistBizCustomerXiezu(this.xiezuform.customerId);
          this.handleXieZuList(this.form.id);
          this.xiezuform.xiezuUsers = [];
        }
      });
    },
    // 查看评论
    handleGetPingLunList(item, isShowPinglun) {
      const param = { customerId: item.id, pageSize: 20 };
      item.isShowPinglun = isShowPinglun;
      if (item.isShowPinglun) {
        listBizCustomerShadowInfoPinglun(param).then((res) => {
          this.pinglunList = res.data.list;
        });
      }
    },

    back() {
      const index = "/biz/customer/index";
      this.$router.push(index);
    },
    fileTypeFormat(type) {
      if (type) {
        return this.selectDictLabel(this.fujianTypeOptions, type);
      } else {
        return "";
      }
    },
    typeFormat(type) {
      if (type) {
        return this.selectDictLabel(this.typeOptions, type);
      } else {
        return "";
      }
    },
    levelFormat(level) {
      if (level) {
        return this.selectDictLabel(this.levelOptions, level);
      } else {
        return "";
      }
    },
    sexFormat(sex) {
      if (sex) {
        return this.selectDictLabel(this.sexOptions, sex);
      } else {
        return "";
      }
    },
    orgTypeFormat(orgType) {
      if (orgType) {
        return this.selectDictLabel(this.orgTypeOptions, orgType);
      } else {
        return "";
      }
    },
    processFormat(process) {
      if (process) {
        return this.selectDictLabel(this.progressOptions, process);
      } else {
        return "";
      }
    },
    ideasTypeFormat(ideasType) {
      if (ideasType) {
        return this.selectDictLabel(this.ideasTypeOptions, ideasType);
      } else {
        return "";
      }
    },
  },
};
